// 舰船管理 Store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Ship, Fleet, Commander, ShipUpgrade, ShipBuildItem } from '@/types'
import { useResourcesStore } from './resources'

export const useShipsStore = defineStore('ships', () => {
  const resourcesStore = useResourcesStore()

  // 状态
  const ships = ref<Record<string, Ship>>({})
  const fleets = ref<Record<string, Fleet>>({})
  const commanders = ref<Record<string, Commander>>({})
  const shipUpgrades = ref<Record<string, ShipUpgrade>>({})
  const shipTemplates = ref<Record<string, Ship>>({})
  const buildQueue = ref<ShipBuildItem[]>([])

  // 计算属性
  const shipsByType = computed(() => {
    const byType: Record<string, Ship[]> = {
      civilian: [],
      military: [],
      research: [],
      special: []
    }

    Object.values(ships.value).forEach(ship => {
      if (!byType[ship.type]) {
        byType[ship.type] = []
      }
      byType[ship.type].push(ship)
    })

    return byType
  })

  const shipsByScale = computed(() => {
    const byScale: Record<string, Ship[]> = {
      tiny: [],
      small: [],
      medium: [],
      large: [],
      huge: [],
      gigantic: []
    }

    Object.values(ships.value).forEach(ship => {
      if (!byScale[ship.scale]) {
        byScale[ship.scale] = []
      }
      byScale[ship.scale].push(ship)
    })

    return byScale
  })

  const totalShipCount = computed(() => {
    return Object.values(ships.value).reduce((total, ship) => total + ship.count, 0)
  })

  const totalFleetPower = computed(() => {
    return Object.values(fleets.value).reduce((total, fleet) => {
      return total + calculateFleetPower(fleet)
    }, 0)
  })

  const availableShips = computed(() => {
    return Object.values(ships.value).filter(ship => {
      // 检查解锁条件
      return checkUnlockConditions(ship.unlockConditions)
    })
  })

  const idleShips = computed(() => {
    const fleetShipIds = new Set<string>()
    Object.values(fleets.value).forEach(fleet => {
      fleet.ships.forEach(fleetShip => {
        fleetShipIds.add(fleetShip.shipId)
      })
    })

    return Object.values(ships.value).filter(ship => !fleetShipIds.has(ship.id))
  })

  // 动作
  function initializeShipTemplates() {
    // 民用舰船模板
    shipTemplates.value['transport'] = {
      id: 'transport',
      name: '运输舰',
      type: 'civilian',
      scale: 'small',
      attributes: {
        crew: 50,
        speed: 8,
        armor: 2,
        shields: 1,
        hull: 100,
        cargo: 1000
      },
      costs: [
        { resourceId: 'metal', amount: 200 },
        { resourceId: 'alloy', amount: 50 },
        { resourceId: 'electronics', amount: 25 }
      ],
      buildTime: 300, // 5分钟
      maintenance: [
        { resourceId: 'energy', amount: 2 }
      ],
      unlockConditions: [],
      upgrades: [],
      icon: 'icon-transport',
      count: 0
    }

    shipTemplates.value['mining_vessel'] = {
      id: 'mining_vessel',
      name: '采矿船',
      type: 'civilian',
      scale: 'medium',
      attributes: {
        crew: 100,
        speed: 5,
        armor: 5,
        shields: 2,
        hull: 200,
        cargo: 500,
        specialAbilities: [
          {
            id: 'mining_laser',
            name: '采矿激光',
            description: '开采小行星资源',
            type: 'utility',
            cooldown: 0,
            energyCost: 10,
            effects: [
              {
                type: 'buff',
                value: 2,
                target: 'self'
              }
            ]
          }
        ]
      },
      costs: [
        { resourceId: 'metal', amount: 400 },
        { resourceId: 'alloy', amount: 100 },
        { resourceId: 'electronics', amount: 75 }
      ],
      buildTime: 600,
      maintenance: [
        { resourceId: 'energy', amount: 5 }
      ],
      unlockConditions: [],
      upgrades: [],
      icon: 'icon-mining',
      count: 0
    }

    // 军用舰船模板
    shipTemplates.value['corvette'] = {
      id: 'corvette',
      name: '护卫舰',
      type: 'military',
      scale: 'small',
      attributes: {
        crew: 80,
        speed: 12,
        armor: 8,
        shields: 5,
        hull: 150,
        weapons: [
          {
            id: 'pulse_laser',
            name: '脉冲激光',
            type: 'energy',
            damage: 15,
            range: 8,
            accuracy: 0.85,
            fireRate: 2,
            energyCost: 5
          }
        ]
      },
      costs: [
        { resourceId: 'metal', amount: 300 },
        { resourceId: 'alloy', amount: 150 },
        { resourceId: 'electronics', amount: 100 }
      ],
      buildTime: 450,
      maintenance: [
        { resourceId: 'energy', amount: 3 },
        { resourceId: 'alloy', amount: 1 }
      ],
      unlockConditions: [],
      upgrades: [],
      icon: 'icon-corvette',
      count: 0
    }

    shipTemplates.value['destroyer'] = {
      id: 'destroyer',
      name: '驱逐舰',
      type: 'military',
      scale: 'medium',
      attributes: {
        crew: 200,
        speed: 9,
        armor: 15,
        shields: 12,
        hull: 400,
        weapons: [
          {
            id: 'kinetic_cannon',
            name: '动能炮',
            type: 'kinetic',
            damage: 35,
            range: 12,
            accuracy: 0.8,
            fireRate: 1.5,
            energyCost: 8
          },
          {
            id: 'missile_launcher',
            name: '导弹发射器',
            type: 'missile',
            damage: 50,
            range: 15,
            accuracy: 0.9,
            fireRate: 0.5,
            energyCost: 15
          }
        ]
      },
      costs: [
        { resourceId: 'metal', amount: 800 },
        { resourceId: 'alloy', amount: 400 },
        { resourceId: 'electronics', amount: 200 }
      ],
      buildTime: 900,
      maintenance: [
        { resourceId: 'energy', amount: 8 },
        { resourceId: 'alloy', amount: 3 }
      ],
      unlockConditions: [],
      upgrades: [],
      icon: 'icon-destroyer',
      count: 0
    }

    // 研究舰船模板
    shipTemplates.value['science_vessel'] = {
      id: 'science_vessel',
      name: '科学舰',
      type: 'research',
      scale: 'medium',
      attributes: {
        crew: 150,
        speed: 7,
        armor: 3,
        shields: 8,
        hull: 250,
        specialAbilities: [
          {
            id: 'deep_scan',
            name: '深度扫描',
            description: '分析未知现象',
            type: 'exploration',
            cooldown: 300,
            energyCost: 50,
            effects: [
              {
                type: 'buff',
                value: 5,
                target: 'area'
              }
            ]
          }
        ]
      },
      costs: [
        { resourceId: 'metal', amount: 500 },
        { resourceId: 'alloy', amount: 200 },
        { resourceId: 'electronics', amount: 300 }
      ],
      buildTime: 750,
      maintenance: [
        { resourceId: 'energy', amount: 6 },
        { resourceId: 'electronics', amount: 2 }
      ],
      unlockConditions: [],
      upgrades: [],
      icon: 'icon-science',
      count: 0
    }
  }

  function buildShip(templateId: string, count: number, shipyardId: string): boolean {
    const template = shipTemplates.value[templateId]
    if (!template) return false

    // 检查解锁条件
    if (!checkUnlockConditions(template.unlockConditions)) return false

    // 计算总成本
    const totalCosts = template.costs.map(cost => ({
      ...cost,
      amount: cost.amount * count
    }))

    // 检查资源
    if (!resourcesStore.canAfford(totalCosts)) return false

    // 扣除资源
    if (!resourcesStore.payCosts(totalCosts)) return false

    // 添加到建造队列
    const buildItem: ShipBuildItem = {
      id: `build_${Date.now()}`,
      shipId: templateId,
      count,
      startTime: Date.now(),
      endTime: Date.now() + template.buildTime * 1000 * count,
      progress: 0,
      shipyardId
    }

    buildQueue.value.push(buildItem)
    return true
  }

  function updateBuildQueue(deltaTime: number) {
    buildQueue.value.forEach((item, index) => {
      const totalTime = item.endTime - item.startTime
      const elapsed = Date.now() - item.startTime
      item.progress = Math.min(elapsed / totalTime, 1)

      if (item.progress >= 1) {
        // 建造完成，添加舰船
        const template = shipTemplates.value[item.shipId]
        if (template) {
          const existingShip = ships.value[item.shipId]
          if (existingShip) {
            existingShip.count += item.count
          } else {
            ships.value[item.shipId] = {
              ...template,
              count: item.count
            }
          }
        }

        // 从队列中移除
        buildQueue.value.splice(index, 1)
      }
    })
  }

  function createFleet(name: string, shipIds: string[]): string {
    const fleetId = `fleet_${Date.now()}`
    
    const fleet: Fleet = {
      id: fleetId,
      name,
      ships: shipIds.map(shipId => ({
        shipId,
        count: 1,
        upgrades: []
      })),
      formation: 'line',
      location: 'home_system',
      status: 'idle'
    }

    fleets.value[fleetId] = fleet
    return fleetId
  }

  function addShipToFleet(fleetId: string, shipId: string, count: number): boolean {
    const fleet = fleets.value[fleetId]
    const ship = ships.value[shipId]
    
    if (!fleet || !ship || ship.count < count) return false

    // 检查舰船是否已在舰队中
    const existingShip = fleet.ships.find(s => s.shipId === shipId)
    if (existingShip) {
      existingShip.count += count
    } else {
      fleet.ships.push({
        shipId,
        count,
        upgrades: []
      })
    }

    // 从可用舰船中扣除
    ship.count -= count
    if (ship.count <= 0) {
      delete ships.value[shipId]
    }

    return true
  }

  function removeShipFromFleet(fleetId: string, shipId: string, count: number): boolean {
    const fleet = fleets.value[fleetId]
    if (!fleet) return false

    const shipIndex = fleet.ships.findIndex(s => s.shipId === shipId)
    if (shipIndex === -1) return false

    const fleetShip = fleet.ships[shipIndex]
    if (fleetShip.count < count) return false

    // 从舰队中移除
    fleetShip.count -= count
    if (fleetShip.count <= 0) {
      fleet.ships.splice(shipIndex, 1)
    }

    // 返回到可用舰船
    const existingShip = ships.value[shipId]
    if (existingShip) {
      existingShip.count += count
    } else {
      const template = shipTemplates.value[shipId]
      if (template) {
        ships.value[shipId] = {
          ...template,
          count
        }
      }
    }

    return true
  }

  function upgradeShip(shipId: string, upgradeId: string): boolean {
    const ship = ships.value[shipId]
    const upgrade = shipUpgrades.value[upgradeId]
    
    if (!ship || !upgrade) return false

    // 检查升级条件
    if (!checkUnlockConditions(upgrade.unlockConditions)) return false

    // 检查成本
    if (!resourcesStore.canAfford(upgrade.costs)) return false

    // 扣除资源
    if (!resourcesStore.payCosts(upgrade.costs)) return false

    // 应用升级效果
    upgrade.effects.forEach(effect => {
      applyUpgradeEffect(ship, effect)
    })

    // 添加升级到舰船
    if (!ship.upgrades.some(u => u.id === upgradeId)) {
      ship.upgrades.push(upgrade)
    }

    return true
  }

  function applyUpgradeEffect(ship: Ship, effect: any) {
    const attribute = effect.attribute as keyof typeof ship.attributes
    const currentValue = ship.attributes[attribute] as number
    
    if (effect.modifier === 'add') {
      (ship.attributes[attribute] as number) = currentValue + effect.value
    } else if (effect.modifier === 'multiply') {
      (ship.attributes[attribute] as number) = currentValue * (1 + effect.value)
    }
  }

  function calculateFleetPower(fleet: Fleet): number {
    return fleet.ships.reduce((power, fleetShip) => {
      const ship = ships.value[fleetShip.shipId] || shipTemplates.value[fleetShip.shipId]
      if (!ship) return power

      const shipPower = calculateShipPower(ship)
      return power + (shipPower * fleetShip.count)
    }, 0)
  }

  function calculateShipPower(ship: Ship): number {
    let power = ship.attributes.hull + ship.attributes.armor + ship.attributes.shields

    // 添加武器威力
    if (ship.attributes.weapons) {
      power += ship.attributes.weapons.reduce((weaponPower, weapon) => {
        return weaponPower + weapon.damage * weapon.fireRate
      }, 0)
    }

    return power
  }

  function moveFleet(fleetId: string, destination: string) {
    const fleet = fleets.value[fleetId]
    if (!fleet) return

    fleet.status = 'moving'
    fleet.location = destination
    
    // 这里可以添加移动逻辑和时间计算
    setTimeout(() => {
      fleet.status = 'idle'
    }, 5000) // 简化的移动时间
  }

  function assignCommander(fleetId: string, commanderId: string): boolean {
    const fleet = fleets.value[fleetId]
    const commander = commanders.value[commanderId]
    
    if (!fleet || !commander) return false

    fleet.commander = commander
    return true
  }

  function checkUnlockConditions(conditions: any[]): boolean {
    // 简化的解锁条件检查
    return true
  }

  function getShip(shipId: string): Ship | undefined {
    return ships.value[shipId] || shipTemplates.value[shipId]
  }

  function getFleet(fleetId: string): Fleet | undefined {
    return fleets.value[fleetId]
  }

  function disbandFleet(fleetId: string): boolean {
    const fleet = fleets.value[fleetId]
    if (!fleet) return false

    // 将所有舰船返回到可用舰船池
    fleet.ships.forEach(fleetShip => {
      const existingShip = ships.value[fleetShip.shipId]
      if (existingShip) {
        existingShip.count += fleetShip.count
      } else {
        const template = shipTemplates.value[fleetShip.shipId]
        if (template) {
          ships.value[fleetShip.shipId] = {
            ...template,
            count: fleetShip.count
          }
        }
      }
    })

    delete fleets.value[fleetId]
    return true
  }

  return {
    // 状态
    ships,
    fleets,
    commanders,
    shipUpgrades,
    shipTemplates,
    buildQueue,
    
    // 计算属性
    shipsByType,
    shipsByScale,
    totalShipCount,
    totalFleetPower,
    availableShips,
    idleShips,
    
    // 动作
    initializeShipTemplates,
    buildShip,
    updateBuildQueue,
    createFleet,
    addShipToFleet,
    removeShipFromFleet,
    upgradeShip,
    moveFleet,
    assignCommander,
    getShip,
    getFleet,
    disbandFleet
  }
})